class Solution(object):
    def maxScore(self, cardPoints, k):
        pre = [0] * k
        suf = [0] * k
        n = len(cardPoints)
        for i in range(k):
            if i == 0:
                pre[i] = cardPoints[i]
                suf[i] = cardPoints[n - 1 - i]
            else:
                pre[i] = pre[i - 1] + cardPoints[i]
                suf[i] = suf[i - 1] + cardPoints[n - 1 - i]
        max_val = max(pre[-1], suf[-1])
        for i in range(k - 1):
            max_val = max(max_val, pre[i] + suf[k - 2 - i])
        return max_val
